package cn.li.security.jwt;

import cn.li.security.jwt.service.IJwtService;


import lombok.Setter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

public class JwtAuthenticationConverter implements AuthenticationConverter {

    @Setter
    private IJwtService iJwtService;

    public JwtAuthenticationConverter(IJwtService iJwtService) {
        this.iJwtService = iJwtService;
    }

    //这里可以判断 是否过期，是否有效
    @Override
    public Authentication convert(HttpServletRequest request) {

        String header = request.getHeader(AUTHORIZATION);
        if (header == null) {
            return null;
        }
        header = header.trim();
        if (!StringUtils.startsWithIgnoreCase(header, iJwtService.getAuthenticationScheme())) {
            return null;
        }
        String token = header.replaceAll(iJwtService.getAuthenticationScheme(),"");
        if(StringUtils.isEmpty(token)){
            return null;
        }
        //解析，获得账号 后进行登录
        String username = (String) iJwtService.retrieve(token);
        try{
            JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(username,token);
            return jwtAuthenticationToken;
        }catch (Exception e){
            //错误了
            throw new BadCredentialsException(
            "Failed to decode basic authentication token");
        }
    }
}
